/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.utils;

import com.koron.common.bean.StaffBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.purpose.domain.JobsStaffTask;
import com.koron.purpose.mapper.JobsStaffTaskMapper;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Service
@EnableScheduling
public class TimingTask {
	private final static  Logger logger = LoggerFactory.getLogger(TimingTask.class);
	
	@Autowired
	private Util util; 
	
	long beginLong;
	long endLong;
	String beginDate = null;
	String endDate = null;
	//每天早上6点10执行，根据岗位任务生成个人工作任务
	@SuppressWarnings("deprecation")
	@Scheduled(cron = "0 0 7 * * ?")
//	@Scheduled(cron = "0 0/3 * * * ?")
	public void produceTask(){
		SessionFactory factory = new SessionFactory();
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String day = dateFormat.format(new Date()); //当前日期
			//查询所有生效的岗位任务
			List<JobsStaffTask> allTask = factory.getMapper(JobsStaffTaskMapper.class).queryAll();
			for (JobsStaffTask jobsStaffTask : allTask) {
				String startDate = dateFormat.format(jobsStaffTask.getStartDate());
				long startLong = dateFormat.parse(startDate).getTime();
				long nowLong = dateFormat.parse(day).getTime();
				if(nowLong < startLong){
					continue;
				}
				getStartAndEndDate(startLong,jobsStaffTask.getCycleLabel(),nowLong);
				if(beginDate == null || endDate == null){
					continue;
				}
				if(day.equals(beginDate)){
					String sourceId = jobsStaffTask.getId();
					int count = factory.getMapper(JobsTasksMapper.class).check(sourceId, beginDate);
					if(count > 0){
						continue;
					}
					
					//生成任务
					JobsTasks task = new JobsTasks();
					task.setId(DefaultIdGenerator.getInstance().generateLongId());
					task.setAddTime(new Date());
					task.setBeginTime(new Date(beginLong));//开始时间
					task.setEndTime(new Date(endLong));	   //结束时间
					task.setStaffCode(jobsStaffTask.getJobsStaffId());//责任人
					MessageBean<?> temp = util.staff(jobsStaffTask.getJobsStaffId(), 0);
					if(0 == temp.getCode() && temp.getData() != null){
						List<StaffBean> list = (List<StaffBean>) temp.getData();
						if(!list.isEmpty() && list.get(0)!=null){
							StaffBean staff = list.get(0);
							task.setStaffName(staff.getName());
						}
					}else{
						task.setStaffName(jobsStaffTask.getJobsStaffId());
					}
					task.setState(0);//执行中
					task.setFstatusflag(0);
					task.setTaskType(jobsStaffTask.getTaskTypeId());
					task.setTaskLabel(jobsStaffTask.getTaskTypeLabel());
					task.setTaskObject(jobsStaffTask.getTaskObjectLabel());
					task.setTaskObjectId(jobsStaffTask.getTaskObjectId());
					task.setTaskDesc(jobsStaffTask.getNote());
					task.setSourceId(sourceId);
					try {
						factory.getMapper(JobsTasksMapper.class).insert(task);
					} catch (Exception e) {
						logger.error(e.toString());
						continue;
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.toString());
		}finally {
			factory.close();
		}
	}
	
	/**
	 * 计算开始时间和结束时间
	 * @param startLong 开始时间
	 * @param cycle 周期
	 * @param nowLong 当前时间戳
	 */
	private void getStartAndEndDate(long startLong,String cycle,long nowLong){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			beginLong = startLong;
			endLong = beginLong;
			long temp =0;
			if("日".equals(cycle)){
				if(nowLong < beginLong){
					beginDate = dateFormat.format(new Date(beginLong));
					endDate = dateFormat.format(new Date(endLong));
				}else{
					beginDate = dateFormat.format(new Date(nowLong));
					endDate = dateFormat.format(new Date(nowLong));
					beginLong = nowLong;
					endLong = nowLong;
				}
				return;
			}
			if("周".equals(cycle)){
				temp = 7*24*60*60*1000;
				//计算日期
//				calculate(temp,nowLong);
				Calendar cale = new GregorianCalendar();
				cale.setFirstDayOfWeek(Calendar.MONDAY);
				cale.setTime(new Date());
				cale.set(Calendar.DAY_OF_WEEK, cale.getFirstDayOfWeek()); // Monday
				beginDate = dateFormat.format(cale.getTime());
				cale.set(Calendar.DAY_OF_WEEK, cale.getFirstDayOfWeek() + 6);
				endDate = dateFormat.format(cale.getTime());
				return;
			}
			if("旬".equals(cycle)){
				temp = 10*24*60*60*1000;
				//计算日期
				calculate(temp,nowLong);
				beginDate = dateFormat.format(new Date(beginLong));
				endDate = dateFormat.format(new Date(endLong));
				return;
			}
			if("月".equals(cycle)){
				//月第一天
				Calendar cale = Calendar.getInstance();
				cale.add(Calendar.MONTH, 0);
				cale.set(Calendar.DAY_OF_MONTH, 1);
				beginDate = dateFormat.format(cale.getTime());
				
				cale = Calendar.getInstance();
				cale.add(Calendar.MONTH, 1);
				cale.set(Calendar.DAY_OF_MONTH, 0);
				endDate = dateFormat.format(cale.getTime());
				return;
			}
			if("季".equals(cycle)){
				Calendar cale = Calendar.getInstance();
				int month = cale.get(Calendar.MONTH) +1;
				if (month >= 1 && month <= 3)
					cale.set(Calendar.MONTH, 0);
				else if (month >= 4 && month <= 6)
					cale.set(Calendar.MONTH, 3);
				else if (month >= 7 && month <= 9)
					cale.set(Calendar.MONTH, 6);
				else if (month >= 10 && month <= 12)
					cale.set(Calendar.MONTH, 9);
				cale.set(Calendar.DATE, 1);
				Date fristDate = cale.getTime();
				beginDate = dateFormat.format(fristDate);
				
				cale = Calendar.getInstance();
				cale.setTime(fristDate);
				cale.add(Calendar.MONTH, 3);
				cale.set(Calendar.DAY_OF_MONTH, 0);
				endDate = dateFormat.format(cale.getTime());
				return;
			}
			if("半年".equals(cycle)){
				Calendar cale = Calendar.getInstance();
				int month = cale.get(Calendar.MONTH) +1;
				if (month >= 1 && month <= 6)
					cale.set(Calendar.MONTH, 0);
				else if (month >= 7 && month <= 12)
					cale.set(Calendar.MONTH, 6);
				cale.set(Calendar.DATE, 1);
				Date fristDate = cale.getTime();
				beginDate = dateFormat.format(fristDate);
				
				cale = Calendar.getInstance();
				cale.setTime(fristDate);
				cale.add(Calendar.MONTH, 6);
				cale.set(Calendar.DAY_OF_MONTH, 0);
				endDate = dateFormat.format(cale.getTime());
				return;
			}
			if("年".equals(cycle)){
				Calendar cale = Calendar.getInstance();
				cale.set(Calendar.MONTH, 0);
				cale.set(Calendar.DATE, 1);
				Date fristDate = cale.getTime();
				beginDate = dateFormat.format(fristDate);
				
				cale = Calendar.getInstance();
				cale.setTime(fristDate);
				cale.add(Calendar.MONTH, 12);
				cale.set(Calendar.DAY_OF_MONTH, 0);
				endDate = dateFormat.format(cale.getTime());
				return;
			}
		} catch (Exception e) {
			logger.error(e.toString());
		}
		beginDate = null;
		endDate = null;
	}
	
	//计算最近的周期
	private void calculate(long cycle,long now){
		endLong+=cycle;
		if(beginLong <= now && now < endLong){
			return;
		}else{
			beginLong = endLong;
			calculate(cycle,now);
		}
	}
}
